package ui.component
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	public class Button extends Sprite
	{
		private var _bitmap:Bitmap;
		private var _upData:BitmapData;
		private var _overData:BitmapData;
		private var _downData:BitmapData;
		
		public var clickFunction:Function;
		
		/////////////////////////////////////////////////////////////////
		/**
		 * @param fun 可以传入带鼠标事件的方法以及不带参数的方法
		 */
		public function Button(upState:BitmapData=null,overState:BitmapData=null,downState:BitmapData=null,fun:Function=null)
		{
			_upData = upState;
			_overData = overState;
			_downData = downState;
			
			clickFunction = fun;
			
			_bitmap = new Bitmap(_upData);
			addChild(_bitmap);
			
			addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
			addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
			addEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
			addEventListener(MouseEvent.CLICK,onClick);
		}
		
		public function dispose():void
		{
			if(_upData)_upData.dispose();
			if(_overData)_overData.dispose();
			if(_downData)_downData.dispose();
			
			removeEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
			removeEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
			removeEventListener(MouseEvent.MOUSE_DOWN,onMouseDown);
			removeEventListener(MouseEvent.MOUSE_UP,onClick);
		}
		/////////////////////////////////////////////////////////////////
		private function onMouseOver(e:MouseEvent):void
		{
			_bitmap.bitmapData = _overData;
		}
		
		private function onMouseOut(e:MouseEvent):void
		{
			_bitmap.bitmapData = _upData;
		}
		
		private function onMouseDown(e:MouseEvent):void
		{
			_bitmap.bitmapData = _downData;
		}
		
		private function onClick(e:MouseEvent):void
		{
			_bitmap.bitmapData = _overData;
			if(clickFunction != null)
			{
				try
				{
					clickFunction(e);
				} 
				catch(e:Error) 
				{
					clickFunction();
				}
				
			}
		}
	}
}